#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

void * start_routine(void * arg);

int main()
{
    int res;
    pthread_t a_thread;

    res = pthread_create(&a_thread,NULL,start_routine,NULL);
    if (res != 0){
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    sleep(3);
    printf("Canceling thread...\n");
//    res = pthread_cancel(a_thread);
    if (res != 0){
        perror("pthread_cancel failed");
        exit(EXIT_FAILURE);
    }

    printf("waiting for thread to finish\n");
    res = pthread_join(a_thread,NULL);
    if (res != 0){
        perror("pthread_join failed");
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}

void * start_routine(void * arg)
{
/*    printf("child Thread is running ,Argument was [%s]\n",(char*)arg);
    sleep(3);
    pthread_exit("Cpu time");
    */

    int i,res;
    res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); 
    if (res != 0){
        perror("pthread_setcancelstate failed");
        exit(EXIT_FAILURE);
    }

    res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
    if (res != 0){
        perror("pthread_setcanceltype failed");
        exit(EXIT_FAILURE);
    }

  
    printf("start_routine is running\n");
    for (i = 0;i < 4;i++){
        printf("Thread is still running (%d)...\n",i);
        sleep(1);

    }
       
    pthread_exit(0);
}
